package com.ea.modular.controller.sys;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ea.common.annotation.LogAnnotation;
import com.ea.common.parent.controller.BaseController;
import com.ea.common.utils.FileUtil;
import com.ea.common.utils.ToolUtil;
import com.ea.modular.model.sys.Office;
import com.ea.modular.model.sys.ShiroUser;
import com.ea.modular.model.sys.User;
import com.ea.modular.service.sys.UserService;
import com.ea.modular.utils.sys.UserUtil;

import io.swagger.annotations.ApiOperation;

/**
 * 用户管理控制器
 * @author jun
 *
 */
@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController{

	@Autowired
	private UserService userService;
	
	@Value("${files.path}")
	private String filesPath;

	private String PREFIX = "/system/user/";
	/**
	 * 跳转到用户主页
	 * @return
	 */
	@ApiOperation(value = "用户首页")
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "",method=RequestMethod.GET)
	public String home() {		 
		return PREFIX + "user";
	}

	/**
	 * 用户列表
	 * @param user
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "用户列表")
	@RequestMapping(value = "/list",method=RequestMethod.POST)
	@ResponseBody
	public Object list(User user){
		return userService.findPage(user);
	}
	/**
	 * 用户详情页
	 * @return
	 */
	@ApiOperation(value = "用户详情")
	@RequestMapping(value = "/form",method=RequestMethod.GET)
	public String form(Model model,User user,String type) {

		//判断是否为修改页
		if(type.equals("update")) {
			User u = UserUtil.getUserById(user.getId());
			String officeId = u.getOfficeId();
			Office poffice = UserUtil.getOfficeById(officeId);
			model.addAttribute("officeName",poffice!=null?poffice.getName():"顶级");
			model.addAttribute("user",u);
			//跳转修改页
			return PREFIX + "user_edit";
		}

		//跳转添加页
		return PREFIX + "user_add";
	}

	/**
	 * 用户管理
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "用户编辑")
	@RequestMapping(value = "/save",method=RequestMethod.POST)
	@ResponseBody
	public int save(User user,String type) {

		//清除用户列表缓存
		UserUtil.clearUserCache();
		//判断是否为修改
		if(type.equals("update")) {
			return userService.update(user);
		}
		int insert = userService.insert(user);
		if(insert>0){
			User u = UserUtil.getUserByLoginName(user.getLoginName());
			String pwd = userService.passwordEncoder(u.getPassword(),u.getId());
			userService.changePwd(u.getId(), pwd);
		}
		return insert;
	}

	/**
	 * 用户删除
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "用户删除")
	@RequestMapping(value = "/delete",method=RequestMethod.POST)
	@ResponseBody
	public int delete(String id) {
		//清除用户列表缓存
		UserUtil.clearUserCache();
		return userService.delete(id);
	}
	/**
	 * 修改默认密码为111111
	 * @param id
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "修改密码")
	@RequestMapping(value = "/change",method=RequestMethod.POST)
	@ResponseBody
	public int changepwd(String id) {
		//清除用户列表缓存
		UserUtil.clearUserCache();
		String pwd = userService.passwordEncoder(new String("111111"),id);
		return userService.changePwd(id, pwd);
	}

	/**
	 * 冻结用户
	 * @param id
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "冻结用户")
	@RequestMapping(value = "/freeze",method=RequestMethod.POST)
	@ResponseBody
	public int freeze(String id){
		//清除用户列表缓存
		UserUtil.clearUserCache();
		return userService.freeze(id, "0");
	}
	/**
	 * 启用用户
	 * @param id
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "启用用户")
	@RequestMapping(value = "/unfreeze",method=RequestMethod.POST)
	@ResponseBody
	public int unfreeze(String id){
		//清除用户列表缓存
		UserUtil.clearUserCache();
		return userService.freeze(id, "1");
	}




	/**
	 * 跳转用户授权页
	 */
	@RequestMapping(value = "/user_assign/{userId}")
	public String role_assign(@PathVariable String userId,Model model) {

		
		User u = UserUtil.getUserById(userId);
		model.addAttribute("userId", u.getId());
		model.addAttribute("loginName", u.getLoginName());
		return PREFIX + "user_roleassign"; 
	}


	/*
	 * 返回String类型的结果
	 * 检查用户名的合法性,如果用户已经存在，返回false，否则返回true(返回json数据，格式为{"valid",true})
	 */
	@RequestMapping(value = "/checkLoginName",method=RequestMethod.POST)
	@ResponseBody
	public String checklogin(String loginName,String id) {

		boolean result = true;
		User u = UserUtil.getUserByLoginName(loginName);
		if(u!=null) {
			if(!u.getId().equals(id)){
				result=false;
			}
		}
		
		return ToolUtil.getValidator(result);
	}


	/*
	 * 返回String类型的结果
	 * 检查工号的合法性,如果工号已经存在，返回false，否则返回true(返回json数据，格式为{"valid",true})
	 */
	@RequestMapping(value = "/checkUserNo",method=RequestMethod.POST)
	@ResponseBody
	public String checkUserNo(String no,String id) {

		boolean result = true;	
		User u = UserUtil.getUserByNo(no);
		if(u!=null) {
			if(!u.getId().equals(id)){
				result=false;
			}
		}
		
		return ToolUtil.getValidator(result);
	}
	
	
	
	/**
	 * 跳转到修改密码页
	 * @return
	 */
	@ApiOperation(value = "修改密码")
	@RequestMapping(value = "/user_chpwd",method=RequestMethod.GET)
	public String user_chpwd(Model model) {	
		model.addAttribute("user", UserUtil.getCurrentUser());
		return PREFIX + "user_chpwd";
	}
	/**
	 * 修改密码
	 * @param id
	 * @param newPwd
	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "冻结用户")
	@RequestMapping(value = "/changePwd",method=RequestMethod.POST)
	@ResponseBody
	public int changePwd(String id,String newPwd,String oldPwd){
		User user = UserUtil.getUserById(id);
		String oldpwd = userService.passwordEncoder(oldPwd,id);
		if(!user.getPassword().equals(oldpwd)) {
			return 0;
		}
		String pwd = userService.passwordEncoder(newPwd,id);
		return userService.changePwd(id, pwd);
	}
	
	
	

	/**
	 * 跳转到个人信息页
	 * @return
	 */
	@ApiOperation(value = "个人信息")
	@RequestMapping(value = "/user_info",method=RequestMethod.GET)
	public String user_info(Model model) {	
		ShiroUser currentUser = UserUtil.getCurrentUser();
		model.addAttribute("user", UserUtil.getUserById(currentUser.getId()));
		model.addAttribute("shirouser", currentUser);
		return PREFIX + "user_view";
	}
	
	
	/**
     * 上传图片
     */
    @RequestMapping(value = "/upload",method=RequestMethod.POST)
    @ResponseBody
    public Object upload(@RequestPart("file") MultipartFile file) {
    	String fileOrigName = file.getOriginalFilename();
		if (!fileOrigName.contains(".")) {
			throw new IllegalArgumentException("缺少后缀名");
		}

		fileOrigName = fileOrigName.substring(fileOrigName.lastIndexOf("."));
		String pathname = FileUtil.getPath() + UUID.randomUUID().toString() + fileOrigName;
		System.out.println(fileOrigName);
		System.out.println(pathname);
		String fullPath = filesPath + pathname;
		FileUtil.saveFile(file, fullPath);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("name", pathname);
		return ToolUtil.getMapToJosn(map);
    }
    
    
    
    /**
	 * 修改个人信息

	 * @return
	 */
	@LogAnnotation
	@ApiOperation(value = "修改个人信息")
	@RequestMapping(value = "/changeInfo",method=RequestMethod.POST)
	@ResponseBody
	public int changeInfo(String id,String avatar,String name,String email,String phone){
		User user = new User();
		user.setId(id);
		user.setPhoto(avatar);
		user.setName(name);
		user.setEmail(email);
		user.setPhone(phone);
		return userService.updateInfo(user);
	}
	
	
    
}
